package main

import (
	"context"
	"os"
	"os/signal"
	"syscall"
	"time"

	generated_v8s_api "v8s-api/rest-api/target/generated-sources"
	"v8s-ssp-proxy/internal/configuration"
	"v8s-ssp-proxy/internal/controller"
	"v8s-ssp-proxy/internal/http"
	"v8s-ssp-proxy/internal/reader"
	"v8s-ssp-proxy/internal/writer"
	"v8s-ssp-proxy/rest/target/generated-sources"
	server "v8s/http-server"
	"v8s/logger"
)

func main() {
	properties := configuration.ReadProperties()

	logger.BuildLogger(properties.Log)

	kafkaWriter := writer.NewWriter(properties.Kafka)
	kafkaReader := reader.NewReader(properties.Kafka)
	v8sClient, err := generated_v8s_api.NewClientWithResponses(properties.V8SApiClient.BaseUrl, generated_v8s_api.WithHTTPClient(properties.V8SApiClient.GetClient()))
	if err != nil {
		panic(err)
	}

	kafkaController := controller.NewController(controller.NewHandlers(kafkaWriter, v8sClient), kafkaReader, kafkaWriter, properties.Kafka)
	handlers := http.NewHandlers(v8sClient)

	apiServer := server.NewServer(properties.APIServer, false)
	managementServer := server.NewServer(properties.Management, true)

	generated.RegisterHandlers(apiServer, handlers)

	ctx, cancel := context.WithCancel(context.Background())
	go kafkaController.Start(ctx)

	go func() {
		log := logger.Logger().Named("main").Sugar()

		// Gracefully Shutdown
		signals := make(chan os.Signal, 1)
		signal.Notify(signals, syscall.SIGTERM, syscall.SIGINT)

		sig := <-signals
		log.Infof("received %s sig, stopping...", sig)

		cancel()

		select {
		case <-ctx.Done():
			os.Exit(0)
		case <-time.After(15 * time.Second):
			log.Fatal("gracefully shutdown timeout")
		}
	}()

	errs := server.RunServers(managementServer, apiServer)

	select {
	case err := <-errs:
		panic(err)
	}
}
